package com.example.Controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.Service.SupplierService;
import com.example.Service.PuOrderService;
import com.example.Service.RawMaterialService;

import com.example.Service.SupplierService;
import com.example.Service.UserService;
import com.example.pojo.PuOrder;
import com.example.pojo.RawMaterial;
import com.example.pojo.Supplier;
import com.example.pojo.User;
import com.example.util.Result;

import io.swagger.annotations.*;

import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;


@RestController
@CrossOrigin
@Api(tags = "采购订单")
@RequestMapping("/PuOrder")
public class PuOrderController {

    @Resource
    private PuOrderService puOrderService;
    @Resource
    private RawMaterialService rawMaterialService;
    @Resource
    private SupplierService supplierService;
    @Resource
    private UserService userService;


    @GetMapping("/getList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "采购订单ID", required = true, dataType = "Integer"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功"),
            @ApiResponse(code = 404, message = "订单不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    @ApiOperation("根据订单ID查询采购订单详情")
    public Result<PuOrder> getOrderDetailById(
            @RequestParam(value = "id") Integer orderId) {

        // 参数校验
        if (orderId == null || orderId <= 0) {
            return new  Result<>("400", "订单ID不能为空且必须大于0");
        }

        // 查询订单基本信息
        PuOrder order = puOrderService.getById(orderId);
        if (order == null) {
            return  new  Result("404", "未找到该订单");
        }

        // 使用 VO 对象封装订单详情
        PuOrder p = new PuOrder();
        BeanUtils.copyProperties(order, p);

        // 查询关联信息
        CompletableFuture<RawMaterial> rawMaterialFuture = CompletableFuture.supplyAsync(() ->
                rawMaterialService.getById(p.getShId()));
        CompletableFuture<Supplier> supplierFuture = CompletableFuture.supplyAsync(() ->
                supplierService.getById(p.getSuId()));
        CompletableFuture<User> userFuture = CompletableFuture.supplyAsync(() ->
                userService.getById(p.getCreateBy()));

        CompletableFuture.allOf(rawMaterialFuture, supplierFuture, userFuture).join();

        return new  Result("200", "查询成功", p);
    }


    //新增采购订单
    @PostMapping
    public Object add(@RequestBody PuOrder puOrder){
        return puOrderService.save(puOrder)?new Result<>("200","新增成功",null):new Result<>("500","新增失败",null);
    }

    //修改采购订单状态
    @PutMapping("updateStatus")
    public Object update(@RequestParam("id") Integer id){
       QueryWrapper<PuOrder> wrapper =new QueryWrapper<>();
       wrapper.eq("id",id);
       PuOrder puOrder = puOrderService.getOne(wrapper);
       if (puOrder.getStatus()==1){
           puOrder.setStatus(2);

       }else if (puOrder.getStatus()==2){
           puOrder.setStatus(3);
           RawMaterial rawMaterial =rawMaterialService.getById(puOrder.getShId());
           rawMaterial.setDeleted(1);
           rawMaterialService.updateById(rawMaterial);
       }
       return puOrderService.updateById(puOrder)?new Result<>("200","修改成功",null):new Result<>("500","修改失败",null);
    }

    //删除采购订单
    @DeleteMapping("/delete{id}")
    public Object delete(@PathVariable Integer id){
        return puOrderService.removeById(id)?new Result<>("200","删除成功",null):new Result<>("500","删除失败",null);
    }

    //查询所有采购订单
    @GetMapping("/selectIs")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "PageSize", value = "页数",dataType = "Integer"),
            @ApiImplicitParam(name = "PageNum", value = "每页条数", dataType = "Integer")
    })
    @ApiOperation("查询所有采购订单")
    public Object selectAll(@RequestParam(value = "PageSize",defaultValue = "1") Integer PageSize,
                            @RequestParam(value = "PageNum",defaultValue = "8") Integer PageNum){
        HashMap<String,Object> map=new HashMap<>();       //创建一个map集合
        Page<PuOrder> page=new Page<>(PageNum,PageSize);  //分页
        QueryWrapper<PuOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("status",2).eq("status",3).eq("status",4);
        Page<PuOrder> puOrderPage = puOrderService.page(page,queryWrapper);
        for (PuOrder p :puOrderPage.getRecords()){
            RawMaterial r = rawMaterialService.getById(p.getShId());  //根据id查询原材料
            p.setShName(r.getName());
            Integer supId = p.getSuId();
            QueryWrapper<Supplier> supplierQueryWrapper=new QueryWrapper<>();
            supplierQueryWrapper.eq("supplier_id",supId);
            Supplier s = supplierService.getOne(supplierQueryWrapper);   //根据id查询供应商
            p.setSuName(s.getSupplierName());
            Integer userId = p.getCreateBy();
            User u = userService.getById(userId);   //根据id查询用户
            p.setCreateName(u.getName());
        }
        map.put("list",puOrderPage.getRecords());
        map.put("total",puOrderPage.getTotal());
        map.put("size",puOrderPage.getSize());
        return  new Result<>("200","查询成功",map);
    }

    @GetMapping("/select")
    public Object select(
            @RequestParam(value = "PageNum") Integer pageNum,
            @RequestParam(value = "PageSize") Integer pageSize) {
        HashMap<String,Object> map=new HashMap<>();       //创建一个map集合
       Page<PuOrder> page = new Page<>(pageNum, pageSize);
       QueryWrapper<PuOrder> queryWrapper = new QueryWrapper<>();
       IPage<PuOrder> puOrderPage = puOrderService.page(page,queryWrapper);
       for (PuOrder p :puOrderPage.getRecords()) {
           // 查询关联信息
           CompletableFuture<RawMaterial> rawMaterialFuture = CompletableFuture.supplyAsync(() ->
                   rawMaterialService.getById(p.getShId()));

           CompletableFuture<Supplier> supplierFuture = CompletableFuture.supplyAsync(() ->
                   supplierService.getById(p.getSuId()));
           CompletableFuture<User> userFuture = CompletableFuture.supplyAsync(() ->
                   userService.getById(p.getCreateBy()));
           CompletableFuture.allOf(rawMaterialFuture, supplierFuture, userFuture).join();

           try {
               RawMaterial r = rawMaterialFuture.get();
               p.setShName(r.getName());
               Supplier s = supplierFuture.get();
               p.setSuName(s.getSupplierName());
               User u = userFuture.get();
               p.setCreateName(u.getName());
           } catch (InterruptedException e) {
               throw new RuntimeException(e);
           } catch (ExecutionException e) {
               throw new RuntimeException(e);
           }

       }
       map.put("list",puOrderPage.getRecords());
       map.put("total",puOrderPage.getTotal());
       map.put("size",puOrderPage.getSize());
       map.put("current",puOrderPage.getCurrent());
       map.put("pages",puOrderPage.getPages());
       return new Result<>("200", "查询成功", map);
    }



}